<?php


namespace app\admin\controller;


use app\admin\model\Node;
use app\admin\model\Role;
use app\admin\validate\RoleValidate;
use think\facade\View;
use think\Response;
use think\response\Json;

class RoleController extends Base
{

    /**
     * 角色列表
     *
     * @return string|\think\response\Json
     */
    public function index(Role $role): string|Json
    {
        if (request()->isAjax()) {

            $param = input('param.');
            $limit = $param['pageSize'];

            $where = [];
            if (!empty($param['searchText'])) {
                $where['role_name'] = ['like', '%' . $param['searchText'] . '%'];
            }

            $selectResult = $role->getRoleByWhere($where, $limit);

            $selectResult->each(function ($v) {
                // 不允许操作超级管理员
                if (1 == $v['id']) {
                    $v['operate'] = '';
                    return false;
                }

                $v['operate'] = showOperate($this->makeButton($v['id']));
            });

            $return['total'] = $selectResult->total();  // 总数据
            $return['rows']  = $selectResult->all();

            return json($return);
        }

        return View::fetch();
    }

    /**
     * 角色添加
     *
     * @param Role $role
     * @param RoleValidate $roleValidate
     * @return string
     */
    public function add(Role $role, RoleValidate $roleValidate): string
    {

        if (request()->isPost()) {

            $param = request()->param();

            $isValid = $roleValidate->check($param);

            if (!$isValid) {
                $this->error($roleValidate->getError());
            }

            $res = $role->save($param);

            if ($res) {
                $this->success('添加成功', (string)url('role/index'));
            } else {
                $this->error('添加失败');
            }

        }


        return View::fetch();

    }

    /**
     * 编辑角色
     *
     * @param Role $role
     * @param RoleValidate $roleValidate
     * @return string
     */
    public function edit(Role $role, RoleValidate $roleValidate): string
    {

        if (request()->isPost()) {

            $param   = request()->param();
            $isValid = $roleValidate->check($param);

            if (!$isValid) {
                $this->error($roleValidate->getError());
            }

            $res = $role::update($param, ['id' => $param['id']]);

            if ($res) {
                $this->success('修改成功', (string)url('role/index'));
            } else {
                $this->error('修改失败');
            }

        }

        $id = input('param.id');
        View::assign([
            'role' => $role->getOneRole($id)
        ]);
        return View::fetch();
    }

    /**
     * 删除角色
     *
     * @param Role $role
     */
    public function delete(Role $role): Response
    {
        $id = input('param.id');

        $res = $role::destroy($id);
        $this->removeRoleCache();

        if ($res) {
            $this->success('删除成功', (string)url('role/index'));
        } else {
            $this->error('删除失败');
        }

    }

    /**
     * 编辑权限
     *
     * @param Node $node
     * @param Role $role
     * @return \think\response\Json
     */
    public function giveAccess(Node $node, Role $role): Json
    {
        $param = input('param.');
        // 获取现在的权限
        if ('get' == $param['type']) {

            $nodeStr = $node->getNodeInfo($param['id']);
            return json(msg(1, $nodeStr, 'success'));
        }

        // 分配新权限
        if ('give' == $param['type']) {

            $doparam = [
                'id'   => $param['id'],
                'rule' => $param['rule']
            ];
            $flag    = $role->editAccess($doparam);

            $this->removeRoleCache();
            return json(msg($flag['code'], $flag['data'], $flag['msg']));
        }
    }

    /**
     * 拼装操作按钮
     * @param $id
     * @return array
     */
    private function makeButton($id): array
    {
        return [
            '编辑'   => [
                'auth'     => 'role/edit',
                'href'     => url('role/edit', ['id' => $id]),
                'btnStyle' => 'primary',
                'icon'     => 'fa fa-paste'
            ],
            '删除'   => [
                'auth'     => 'role/delete',
                'href'     => "javascript:roleDel(" . $id . ")",
                'btnStyle' => 'danger',
                'icon'     => 'fa fa-trash-o'
            ],
            '分配权限' => [
                'auth'     => 'role/giveaccess',
                'href'     => "javascript:giveQx(" . $id . ")",
                'btnStyle' => 'info',
                'icon'     => 'fa fa-institution'
            ],
        ];
    }

}